import { addNewClockTime, getClockTimeList, updateClockTime } from "../../service/index"

// pages/hourList/index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    currentMouth: new Date().getMonth() + 1 + '月',
    dialogShow: false, // 添加打卡记录弹框开关
    day: new Date().toLocaleDateString(), // 打卡当天日期
    clockTime: '08:20', // 打卡时间点
    selected: undefined,
    toDays: [
      {
        value: 'am',
        key: 'zsh',
        label: '上班'
      },
      {
        value: 'pm',
        key: 'wsh',
        label: '下班'
      }
    ],
    clockTimeList: [],
  },

  setDay(e) {
    this.setData({
      day: e.detail.value
    })
  },
  radioChange(e) {
    const value = e.detail.value
    const selected = this.data.toDays.filter(item => item.value === value)[0]
    this.setData({
      selected
    })
  },

  takeTodayHour() {
    this.setData({ dialogShow: true })
  },
  closeDialog() {
    this.setData({ dialogShow: false })
  },
  bindTimeChange(e) {
    this.setData({
      clockTime: e.detail.value
    })
  },
  /**
   * 记录当天时长提交
   */
  submitTodayHour() {
    const that = this
    const { selected, clockTime, day, clockTimeList } = this.data
    if (selected && clockTime && day) {
      wx.showModal({
        title: '确认提交时间',
        content: `${day},${selected.label},${clockTime}`,
        async success(res) {
          if (res.confirm) {
            // 对比本地列表判断是新增还是编辑
            const isEdit = clockTimeList.find(item => {
              return item.date === day
            })

            if (isEdit) {
              updateClockTime({
                prev_data: isEdit,
                current_date: day,
                clock_time: clockTime,
                clock_type: selected.value,
              }).then(that.handelResult)
            } else {
              updateClockTime({
                clock_time: clockTime,
                clock_type: selected.value,
                current_date: day
              }).then(that.handelResult)
            }

          }
        }
      })
    } else {
      wx.showToast({
        title: '请选择时间',
        icon: 'none'
      })
      return
    }
  },


  fetchClockTimeListData() {
    getClockTimeList().then(data => {
      this.setData({
        clockTimeList: data
      })
    })
  },

  handelResult() {
    const that = this
    wx.showToast({
      title: "操作成功",
    })
    that.setData({
      dialogShow: false
    }).then(() => {
      that.fetchClockTimeListData()
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.fetchClockTimeListData()
  },

})